import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../constants/app_theme.dart';

/// 自定义应用栏组件
/// 提供统一的应用栏样式和功能
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 标题
  final String title;
  
  /// 副标题
  final String? subtitle;
  
  /// 是否显示返回按钮
  final bool showBackButton;
  
  /// 自定义返回按钮回调
  final VoidCallback? onBackPressed;
  
  /// 操作按钮列表
  final List<Widget>? actions;
  
  /// 是否使用渐变背景
  final bool useGradient;
  
  /// 背景颜色
  final Color? backgroundColor;
  
  /// 文字颜色
  final Color? textColor;
  
  /// 是否居中标题
  final bool centerTitle;
  
  /// 高度
  final double height;
  
  /// 是否显示阴影
  final bool showShadow;
  
  /// 底部组件
  final PreferredSizeWidget? bottom;

  const CustomAppBar({
    super.key,
    required this.title,
    this.subtitle,
    this.showBackButton = true,
    this.onBackPressed,
    this.actions,
    this.useGradient = true,
    this.backgroundColor,
    this.textColor,
    this.centerTitle = false,
    this.height = kToolbarHeight,
    this.showShadow = true,
    this.bottom,
  });

  @override
  Widget build(BuildContext context) {
    final bool canPop = Navigator.canPop(context);
    final Color finalTextColor = textColor ?? 
        (useGradient ? Colors.white : AppTheme.textPrimaryColor);
    
    return AppBar(
      title: _buildTitle(finalTextColor),
      centerTitle: centerTitle,
      backgroundColor: backgroundColor ?? 
          (useGradient ? Colors.transparent : AppTheme.surfaceColor),
      foregroundColor: finalTextColor,
      elevation: showShadow ? 2 : 0,
      shadowColor: Colors.black.withOpacity(0.1),
      systemOverlayStyle: SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: useGradient 
            ? Brightness.light 
            : Brightness.dark,
        statusBarBrightness: useGradient 
            ? Brightness.dark 
            : Brightness.light,
      ),
      leading: _buildLeading(context, canPop, finalTextColor),
      actions: actions,
      bottom: bottom,
      flexibleSpace: useGradient ? _buildGradientBackground() : null,
    );
  }

  /// 构建标题
  Widget _buildTitle(Color textColor) {
    if (subtitle != null) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: centerTitle 
            ? CrossAxisAlignment.center 
            : CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: textColor,
            ),
          ),
          Text(
            subtitle!,
            style: TextStyle(
              fontSize: 12,
              color: textColor.withOpacity(0.8),
            ),
          ),
        ],
      );
    }
    
    return Text(
      title,
      style: TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.bold,
        color: textColor,
      ),
    );
  }

  /// 构建返回按钮
  Widget? _buildLeading(BuildContext context, bool canPop, Color textColor) {
    if (!showBackButton || !canPop) return null;
    
    return IconButton(
      icon: Icon(
        Icons.arrow_back_ios,
        color: textColor,
      ),
      onPressed: onBackPressed ?? () => Navigator.pop(context),
    );
  }

  /// 构建渐变背景
  Widget _buildGradientBackground() {
    return Container(
      decoration: BoxDecoration(
        gradient: AppTheme.primaryGradient,
      ),
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(
    height + (bottom?.preferredSize.height ?? 0),
  );
}

/// 简单应用栏
/// 用于简单页面的应用栏
class SimpleAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 标题
  final String title;
  
  /// 操作按钮列表
  final List<Widget>? actions;
  
  /// 是否显示返回按钮
  final bool showBackButton;

  const SimpleAppBar({
    super.key,
    required this.title,
    this.actions,
    this.showBackButton = true,
  });

  @override
  Widget build(BuildContext context) {
    return CustomAppBar(
      title: title,
      actions: actions,
      showBackButton: showBackButton,
      useGradient: false,
      centerTitle: true,
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

/// 渐变应用栏
/// 用于主要页面的应用栏
class GradientAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 标题
  final String title;
  
  /// 副标题
  final String? subtitle;
  
  /// 操作按钮列表
  final List<Widget>? actions;
  
  /// 是否显示返回按钮
  final bool showBackButton;
  
  /// 高度
  final double height;

  const GradientAppBar({
    super.key,
    required this.title,
    this.subtitle,
    this.actions,
    this.showBackButton = true,
    this.height = kToolbarHeight,
  });

  @override
  Widget build(BuildContext context) {
    return CustomAppBar(
      title: title,
      subtitle: subtitle,
      actions: actions,
      showBackButton: showBackButton,
      useGradient: true,
      height: height,
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(height);
}

/// 搜索应用栏
/// 用于搜索页面的应用栏
class SearchAppBar extends StatefulWidget implements PreferredSizeWidget {
  /// 搜索提示文本
  final String hintText;
  
  /// 搜索回调
  final Function(String) onSearch;
  
  /// 搜索变化回调
  final Function(String)? onSearchChanged;
  
  /// 取消回调
  final VoidCallback? onCancel;
  
  /// 初始搜索文本
  final String? initialText;
  
  /// 是否自动聚焦
  final bool autofocus;

  const SearchAppBar({
    super.key,
    required this.hintText,
    required this.onSearch,
    this.onSearchChanged,
    this.onCancel,
    this.initialText,
    this.autofocus = true,
  });

  @override
  State<SearchAppBar> createState() => _SearchAppBarState();

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}

class _SearchAppBarState extends State<SearchAppBar> {
  late TextEditingController _controller;
  late FocusNode _focusNode;

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.initialText);
    _focusNode = FocusNode();
    
    if (widget.autofocus) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _focusNode.requestFocus();
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  /// 清空搜索
  void _clearSearch() {
    _controller.clear();
    widget.onSearchChanged?.call('');
    _focusNode.requestFocus();
  }

  /// 提交搜索
  void _submitSearch() {
    widget.onSearch(_controller.text.trim());
    _focusNode.unfocus();
  }

  @override
  Widget build(BuildContext context) {
    return AppBar(
      backgroundColor: AppTheme.surfaceColor,
      elevation: 1,
      shadowColor: Colors.black.withOpacity(0.1),
      leading: IconButton(
        icon: const Icon(Icons.arrow_back),
        onPressed: widget.onCancel ?? () => Navigator.pop(context),
      ),
      title: TextField(
        controller: _controller,
        focusNode: _focusNode,
        decoration: InputDecoration(
          hintText: widget.hintText,
          hintStyle: TextStyle(
            color: AppTheme.textSecondaryColor,
          ),
          border: InputBorder.none,
          suffixIcon: _controller.text.isNotEmpty
              ? IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: _clearSearch,
                )
              : null,
        ),
        style: TextStyle(
          color: AppTheme.textPrimaryColor,
          fontSize: 16,
        ),
        textInputAction: TextInputAction.search,
        onChanged: (value) {
          setState(() {});
          widget.onSearchChanged?.call(value);
        },
        onSubmitted: (_) => _submitSearch(),
      ),
      actions: [
        TextButton(
          onPressed: _submitSearch,
          child: Text(
            '搜索',
            style: TextStyle(
              color: AppTheme.primaryColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }
}

/// 标签页应用栏
/// 用于带标签页的应用栏
class TabAppBar extends StatelessWidget implements PreferredSizeWidget {
  /// 标题
  final String title;
  
  /// 标签页列表
  final List<Tab> tabs;
  
  /// 标签页控制器
  final TabController? controller;
  
  /// 操作按钮列表
  final List<Widget>? actions;
  
  /// 是否显示返回按钮
  final bool showBackButton;
  
  /// 是否使用渐变背景
  final bool useGradient;

  const TabAppBar({
    super.key,
    required this.title,
    required this.tabs,
    this.controller,
    this.actions,
    this.showBackButton = true,
    this.useGradient = true,
  });

  @override
  Widget build(BuildContext context) {
    return CustomAppBar(
      title: title,
      actions: actions,
      showBackButton: showBackButton,
      useGradient: useGradient,
      bottom: TabBar(
        controller: controller,
        tabs: tabs,
        indicatorColor: useGradient ? Colors.white : AppTheme.primaryColor,
        labelColor: useGradient ? Colors.white : AppTheme.primaryColor,
        unselectedLabelColor: useGradient 
            ? Colors.white.withOpacity(0.7) 
            : AppTheme.textSecondaryColor,
        indicatorWeight: 3,
        labelStyle: const TextStyle(
          fontWeight: FontWeight.bold,
        ),
        unselectedLabelStyle: const TextStyle(
          fontWeight: FontWeight.normal,
        ),
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(
    kToolbarHeight + kTextTabBarHeight,
  );
}